package com.ytrsoft.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.setting.Setting;
import com.github.houbb.opencc4j.util.ZhConverterUtil;
import com.ytrsoft.entity.Model;
import com.ytrsoft.entity.Params;

import java.util.ArrayList;
import java.util.List;

public final class Request {

    private static final String BASE_API_URL = "https://api.lyricist.ai";
    private static final String URL_GENERATE_LYRICS = BASE_API_URL + "/lyrics/generator";
    private static final String URL_FETCH_PARAMETERS = BASE_API_URL + "/lyrics/parameters";
    private static final String URL_FETCH_PARAMETERS_V2 = BASE_API_URL + "/post/parameters";

    private static final String TOKEN_KEY = "token";
    private static final String AUTH_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";
    private static final String CONTENT_TYPE_HEADER = "Content-Type";
    private static final String CONTENT_TYPE_JSON = "application/json";

    private static final Log log = LogFactory.get();

    private Request() {
        throw new UnsupportedOperationException();
    }

    public static List<String> generateLyrics(Params params) {
        String token = getToken();
        String requestBody = JSONUtil.toJsonStr(params);
        String response = sendPost(URL_GENERATE_LYRICS, token, ZhConverterUtil.toTraditional(requestBody));
        return parseLyrics(response);
    }

    public static List<Model> fetchModels() {
        String token = getToken();
        String response = sendGet(URL_FETCH_PARAMETERS, token);
        return parseModels(response);
    }

    public static List<Model> fetchV2Models() {
        String token = getToken();
        String response = sendGet(URL_FETCH_PARAMETERS_V2, token);
        return parseModels(response);
    }

    private static String getToken() {
        return new Setting("config.properties").getStr(TOKEN_KEY);
    }

    private static String sendGet(String url, String token) {
        return HttpRequest.get(url)
                .header(AUTH_HEADER, BEARER_PREFIX + token)
                .header(CONTENT_TYPE_HEADER, CONTENT_TYPE_JSON)
                .execute()
                .body();
    }

    private static String sendPost(String url, String token, String body) {
        log.info(body);
        return HttpRequest.post(url)
                .header(AUTH_HEADER, BEARER_PREFIX + token)
                .header(CONTENT_TYPE_HEADER, CONTENT_TYPE_JSON)
                .body(body)
                .execute()
                .body();
    }

    private static List<String> parseLyrics(String response) {
        JSONObject jsonResponse = JSONUtil.parseObj(response);
        if (isSuccessResponse(jsonResponse)) {
            JSONArray data = jsonResponse.getJSONArray("data");
            return convertToSimplified(data.toList(String.class));
        }
        return new ArrayList<>();
    }

    private static List<Model> parseModels(String response) {
        JSONObject jsonResponse = JSONUtil.parseObj(response);
        if (isSuccessResponse(jsonResponse)) {
            JSONObject dataObj = JSONUtil.parseObj(ZhConverterUtil.toSimple(jsonResponse.getStr("data")));
            return dataObj.getJSONArray("models").toList(Model.class);
        }
        return new ArrayList<>();
    }

    private static boolean isSuccessResponse(JSONObject response) {
        return "success".equals(response.getStr("status"));
    }

    private static List<String> convertToSimplified(List<String> traditionalList) {
        List<String> simplifiedList = new ArrayList<>();
        for (String sentence : traditionalList) {
            simplifiedList.add(ZhConverterUtil.toSimple(sentence));
        }
        return simplifiedList;
    }
}
